package com.origin.oss.manager;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.oss.model.PartETag;
import com.origin.oss.specification.domain.multipart.SliceUploadInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yezh
 * @date 2024/2/5 15:10
 */
@Component
public class AliOssUploadManager {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String PART_ETAG = "uploader:partETags:";
    private static final String UPLOAD_PART_REQUEST = "uploader:uploadPartRequest:";

    public void storePartETag(PartETag partETag, String identifier) {
        redisTemplate.opsForList().rightPush(PART_ETAG + identifier, JSON.toJSONString(partETag));
    }

    public List<PartETag> listPartETag(String identifier) {
        List<String> partETagList = redisTemplate.opsForList().range(PART_ETAG + identifier, 0, -1);
        return CollUtil.isEmpty(partETagList)
                ? Collections.emptyList()
                : partETagList.stream().map(item -> JSON.parseObject(item, PartETag.class)).collect(Collectors.toList());
    }

    public long countPartETag(String identifier) {
        return redisTemplate.opsForList().size(PART_ETAG + identifier);
    }

    public void storeUploadPartRequest(SliceUploadInfo uploadFileInfo, String identifier) {
        redisTemplate.opsForValue()
                .set(UPLOAD_PART_REQUEST + identifier, JSON.toJSONString(uploadFileInfo));
    }

    public SliceUploadInfo getSliceUploadInfo(String identifier) {
        return JSON.parseObject(redisTemplate.opsForValue().get(UPLOAD_PART_REQUEST + identifier), SliceUploadInfo.class);
    }

    public void clearCache(String identifier) {
        redisTemplate.delete(PART_ETAG + identifier);
        redisTemplate.delete(UPLOAD_PART_REQUEST + identifier);
    }

}
